#include <errno.h>
#include <signal.h>
#include <string>
#include <iostream>
#include <netinet/in.h>
#include <tsubamegaeshi-base/behavior.h>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>

#include <tsubamegaeshi-base/soccerbotbehavior.h>
#include <tsubamegaeshi-base/worldmodel.h>
#include <tsubamegaeshi-base/connection.h>
#include <tsubamegaeshi-base/agent.h>

//#include <sample/sampleaction.h>
#include <naito/naitoaction.h>

using namespace rcss::net;
using namespace std;
using namespace boost;

string gHost = "127.0.0.1";
string gTeam = "TsubameGaeshi";
int gPort = 3100;
Agent::shared_ptr a;

void PrintGreeting()
{
    cout << "tsubamegaeshi-base, a robocup 3d soccer agent" << endl
         << "Copyright (C) 2007 Takenori KUBO." << endl  << endl;

}

void PrintHelp()
{
    cout << "\nusage: tsubamegaeshi-base [options]" << endl;
    cout << "\noptions:" << endl;
    cout << " --help      prints this message." << endl;
    cout << " --host=IP   IP of the server." << endl;
    cout << " --team=NAME NAME of the team." << endl;
    cout << "\n";
}

void ReadOptions(int argc, char* argv[])
{
    for( int i = 0; i < argc; i++) {
        if ( strcmp( argv[i], "--help" ) == 0 )  {
            PrintHelp();
            exit(0);
        } else if ( strncmp( argv[i], "--host", 6 ) == 0 ) {
            string tmp=argv[i];
                
            if ( tmp.length() <= 7 ) { // minimal sanity check
                PrintHelp();
                exit(0);
            }
            gHost = tmp.substr(7);
        } else if ( strncmp( argv[i], "--team", 6 ) == 0 ) {
            string tmp=argv[i];
                
            if ( tmp.length() <= 7 ) { // minimal sanity check
                PrintHelp();
                exit(0);
            }
            gTeam = tmp.substr(7);
        }
    }
}


// SIGINT handler prototype
extern "C" void handler(int sig)
{
    if (sig == SIGINT) {
        a->stop();
    }
}

int
main(int argc, char* argv[])
{
    // registering the handler, catching SIGINT signals 
    signal(SIGINT, handler);

    PrintGreeting();
    ReadOptions(argc,argv);

    try {
        Worldmodel::shared_ptr wp(new Worldmodel(gTeam));
        Action::shared_ptr     act(new Naitoaction(wp));
        //Action::shared_ptr     act(new Sampleaction(wp));
        Behavior::shared_ptr   behavior(new SoccerbotBehavior(wp, act));
        a = Agent::shared_ptr(new Agent(behavior, gHost, gPort));
        a->run();

    } catch (rcss::net::BindErr error) {
        std::cerr << "failed to bind socket with '"
                  << error.what() << "'" << std::endl;
    } catch (rcss::net::ConnectErr error) {
        std::cerr << "connection failed with: '"
                  << error.what() << "'" << std::endl;
    }
    a->done();

}
